#!/usr/bin/env bash
# 安装 GDB（无 sudo）
set -euo pipefail

PREFIX="$HOME/local"
VERSION="13.2"
JOBS=$(nproc 2>/dev/null || echo 2)

echo "==> 安装路径: $PREFIX"
mkdir -p "$PREFIX"

# 写入环境变量（若不存在则追加）
grep -q '### gdb-user-install' ~/.bashrc 2>/dev/null || {
cat >> ~/.bashrc <<EOF

### gdb-user-install
export PATH="$PREFIX/bin:\$PATH"
export LD_LIBRARY_PATH="$PREFIX/lib:\$LD_LIBRARY_PATH"
### gdb-user-install
EOF
}

source ~/.bashrc || true

# 下载源码
cd /tmp
wget -q https://ftp.gnu.org/gnu/gdb/gdb-${VERSION}.tar.xz
tar -xf gdb-${VERSION}.tar.xz
cd gdb-${VERSION}

# 编译并安装
./configure --prefix="$PREFIX" --disable-werror
make -j"$JOBS"
make install

# 验证
echo
echo "✅ GDB 安装完成："
"$PREFIX/bin/gdb" --version | head -n1
echo
echo "请重新打开终端或执行："
echo "  source ~/.bashrc"
echo "以便 PATH 生效。"
